import React from 'react';
import Goods from './goods';
import { GoodsListStyle } from './style';
import type { ShopingCartState, ShopingCartGoods } from '@/models/shopingCart';
import type { ShopingCartProps } from './ShopingCart';
import { connect } from 'umi';

export type HandleGoods = (goods: ShopingCartGoods) => void;

export type GoodsListProps = {
  catgrayGoodsList: any[];
  catgrayName: string | undefined;
} & ShopingCartProps;

const GoodsList: React.FC<GoodsListProps> = (props) => {
  for (let k = 0; k < props.catgrayGoodsList.length; k++) {
    const z = props.catgrayGoodsList[k];
    z.num = 0;
  }

  for (let j = 0; j < props.catgrayGoodsList.length; j++) {
    const y = props.catgrayGoodsList[j];
    for (let i = 0; i < props.shopingCartGoodslist?.goodsList.length; i++) {
      const x = props.shopingCartGoodslist?.goodsList[i];
      if (x.gid === y.id) {
        console.log('匹配');
        y.num = x.num;
        continue;
      }
    }
  }

  return (
    <GoodsListStyle>
      <p className="catgray-name">{props.catgrayName}</p>
      {props.catgrayGoodsList?.length >= 0 &&
        props.catgrayGoodsList.map((item, key) => {
          return (
            <ul className="goods-list" key={item.id}>
              <Goods
                num={item.num ? item.num : 0}
                gid={item.id}
                name={item.name}
                goodsdetail={item.remark}
                gimg={item.albumpath}
                gprice={item.posprice}
                plusGoods={props.addGoods}
                reduceGoods={props.reduceGoods}
                rawGoods={item}
              />
            </ul>
          );
        })}
    </GoodsListStyle>
  );
};

export default connect(
  ({ shopingcart }: { shopingcart: ShopingCartState }) => {
    return {
      shopingCartGoodslist: shopingcart,
    };
  },
  (dispatch) => {
    return {
      addGoods: (goods: ShopingCartGoods) => {
        dispatch({
          type: 'shopingcart/plus',
          data: goods,
        });
      },
      reduceGoods: (goods: ShopingCartGoods) => {
        dispatch({
          type: 'shopingcart/reduce',
          data: goods,
        });
      },
    };
  },
)(GoodsList);
